package com.backstage.controller;

import com.backstage.pojo.Chatroom;
import com.backstage.pojo.Scope;
import com.backstage.pojo.User;
import com.backstage.service.ChatroomService;
import com.backstage.service.ScopeService;
import com.backstage.service.UserService;
import com.backstage.utils.CommonDate;
import com.backstage.webSocket.ChatMessageHandler;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;

import java.util.List;


@Controller
@RequestMapping(value = "/chat")
public class WebSocketController {
    @Autowired
    private UserService userService;

    @Autowired
    private ChatroomService chatroomService;

    @Autowired
    private ScopeService scopeService;

    @Bean//这个注解会从Spring容器拿出Bean
    public ChatMessageHandler infoHandler() {
        return new ChatMessageHandler();
    }

    /**
     * 进入首页
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = {"/","/index"}, method = RequestMethod.GET)
    public String webhtmlChatIndex(HttpSession session, Model model){
        int scopeId = Integer.parseInt(session.getAttribute("RANGE_ID").toString());
        int userId = Integer.parseInt(session.getAttribute("SESSION_USERID").toString());
        List<Chatroom> list = chatroomService.selectChatroomScopeIdList(scopeId,userId);
        model.addAttribute("list",list);
        model.addAttribute("scopeId",scopeId);
        return "chat/index";
    }

    /**
     * 进入聊天室
     * @param chatid 聊天室ID
     * @param request
     * @param response
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "{chatid}/details", method = RequestMethod.GET)
    public String webHtmlChatDetails(@PathVariable("chatid") Integer chatid, HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) {
        //区域ID
        int scopeId = Integer.parseInt(session.getAttribute("RANGE_ID").toString());
        //用户ID
        int userId = Integer.parseInt(session.getAttribute("SESSION_USERID").toString());
        //Chatroom newGetChat = chatroomService.selectChatroomGetId(chatid);
        Chatroom newGetChat = chatroomService.selectChatroomHas(scopeId, userId, chatid);
        Boolean hasScope = newGetChat != null;
        model.addAttribute("hasScope", hasScope);
        if(hasScope){ //当前用户“在”此区
            model.addAttribute("chatroom", newGetChat);
            session.setAttribute("CHAT_ID", chatid);
        }
        return "chat/details";
    }

    /**
     * 登陆页面 路由
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginPage(HttpServletRequest request, HttpServletResponse response) {
        return "chat/login";
    }

    /**
     * 进入注册 路由
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/join", method = RequestMethod.GET)
    public String joinPage(HttpServletRequest request, HttpServletResponse response) {
        return "chat/join";
    }

    /**
     * 退出用户
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/websocket/logout", method = RequestMethod.GET)
    public String chatLogout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        session.removeAttribute("SESSION_USERID");
        session.removeAttribute("RANGE_ID");
        session.removeAttribute("CHAT_ID");
        return "redirect:/chat/index";
    }

    /**
     * 登陆用户
     * @param rangez 经度坐标
     * @param rangey 纬度坐标
     * @param username 用户名
     * @param password 密码
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/websocket/login", method = RequestMethod.POST)
    public String websocketLogin(@RequestParam(required = true) float rangez,
                        @RequestParam(required = true) float rangey,
                        @RequestParam(required = true) String username,
                        @RequestParam(required = true) String password,
                        HttpServletRequest request,
                        Model model
    ) {
        if("".equals(rangez) || "".equals(rangey)){
            model.addAttribute("errMsg", "请获取经纬度坐标");
            return "chat/login";
        }

        User socketUser = userService.selectHasUserName(username);
        if(socketUser == null){
            model.addAttribute("errMsg", "用户不存在");
            return "chat/login";
        }

        String passA = socketUser.getPassword();
        if(!passA.equals(password)){
            model.addAttribute("errMsg", "密码错误");
            return "chat/login";
        }

        int[] range_china = new int[] {73500000,53600000,135500000,1000000}; //全中国 300+W条数据
        //int[] range_shanghai = new int[]{121044451,31923898,1220747,30659998}; //上海范围 20+W
        int rangeKm = 30000;
        int rangeX = Math.round(rangez * 1000000);
        int rangeY = Math.round(rangey * 1000000);
        int total_range = (int) Math.ceil((range_china[1] - range_china[3]) / rangeKm);//一列总共几个区域
        int range_start = rangeX - range_china[0]; //原点x
        int range_end = range_china[1] - rangeY; //原点y
        int range_location_x = (int) Math.floor(range_start / rangeKm); //在一行中的“第几个”区域
        int range_location_y = (int) Math.floor(range_end / rangeKm); //在列中的“第几个”区域
        int range_location_n = range_location_x * total_range + range_location_y; //所在区域

        if(range_location_x<0 || range_location_y<0){
            model.addAttribute("errMsg", "您所在坐标不在服务区域内。");
            return "chat/login";
        }

        //查询区域是否存在
        int scopeId = chatroomService.selectChatroomScopeId(range_location_n);
        if(scopeId == 0){
            //创建区域
            Scope newScope = new Scope();
            newScope.setScopeid(range_location_n);
            newScope.setCreattime(CommonDate.newData());
            DecimalFormat df = new DecimalFormat(".000000");//保留6位小数
            int x1 = range_china[0] + range_location_x * rangeKm;
            int x2 = range_china[1] - range_location_y * rangeKm;
            int x3 = range_china[0] + rangeKm + range_location_x * rangeKm;
            int x4 = range_china[1] - rangeKm - range_location_y * rangeKm;
            int x0 = 1000000;
            String[] coordinateArr = {df.format((double) x1/x0),  df.format((double) x2/x0), df.format((double) x3/x0), df.format((double) x4/x0)};
            //String coordinate = Arrays.toString(coordinateArr).replaceAll("\\[|\\]|\\s", "");
            String coordinate = StringUtils.join(coordinateArr,",");
            newScope.setCoordinate(coordinate);
            scopeService.selectInsertNewScope(newScope);

            //创建区域“聊天室”
            Chatroom newChatroom = new Chatroom();
            newChatroom.setTitle(""+range_location_n+"");
            newChatroom.setTotalusers(1000);
            newChatroom.setOnlineusers(0);
            newChatroom.setScopeid(range_location_n);
            newChatroom.setStatus(1);
            newChatroom.setStatustime(CommonDate.newData());
            chatroomService.selectInsertNewChatroom(newChatroom);
        }
        HttpSession session = request.getSession(false);
        session.setAttribute("SESSION_USERID",socketUser.getId());
        session.setAttribute("RANGE_ID",range_location_n);
        session.setAttribute("SESSION_USER_NAME", socketUser.getNickname());
        socketUser.setSigntime(CommonDate.newData());
        int upDataSignTime = userService.selectUpDataSignTime(socketUser);
        return "redirect:/chat/index";
    }

    /**
     * 注册用户
     * @param username 用户名
     * @param password 密码
     * @param passwordA 重复密码
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/websocket/join", method = RequestMethod.POST)
    public String websocketJoin(@RequestParam(required = true) String username,
                                @RequestParam(required = true) String password,
                                @RequestParam(required = true) String passwordA,
                                HttpServletRequest request,
                                Model model
    ) {
        if("".equals(password) || "".equals(username)){
            model.addAttribute("errMsg", "用户名或密码不能为空");
            return "chat/join";
        }

        if(username.length() > 20){
            model.addAttribute("errMsg", "用户名不能大于20个字符");
            return "chat/join";
        }

        if(!password.equals(passwordA)){
            model.addAttribute("errMsg", "重复密码不相等");
            return "chat/join";
        }

        User socketUser = userService.selectHasUserName(username);
        if(socketUser != null && socketUser.getName().equals(username)){
            model.addAttribute("errMsg", "用户名已存在");
            return "chat/join";
        }

        User newUser = new User();
        newUser.setName(username);
        newUser.setPassword(password);
        newUser.setNickname(username);
        newUser.setSigntime(CommonDate.newData());
        newUser.setCreattime(CommonDate.newData());
        newUser.setStatus(1);

        int addId = userService.selectInsertUser(newUser);
        //HttpSession session = request.getSession(false);
        //session.setAttribute("chat_user",addId);
        //session.setAttribute("chat_userName",username);
        return "chat/login";
    }

//    @RequestMapping("/websocket/send")
//    @ResponseBody
//    public String send(HttpServletRequest request) {
//        String username = request.getParameter("username");
//        infoHandler().sendMessageToUser(username, new TextMessage("你好，测试！！！！"));
//        return null;
//    }
//
//
//    @RequestMapping("/websocket/broad")
//    @ResponseBody
//    public String broad() {
//        infoHandler().sendMessageToUsers(new TextMessage("发送一条小Broad"));
//        System.out.println("群发成功");
//        return "broad";
//    }
}